using System;
using System.Collections.Generic;
using System.Web;
using System.Web.Mvc;
using Cosmicvent.Ajd.Core;
using Cosmicvent.Ajd.Core.Domain.Model;
using Cosmicvent.Ajd.UI.Infrastructure.Filters;
using Cosmicvent.Ajd.Core.Services;
using Cosmicvent.Ajd.UI.Infrastructure.Services;
using Cosmicvent.Ajd.UI.Infrastructure.Mvc;

namespace Cosmicvent.Ajd.UI.Controllers {
    [RequiresAuthentication(Role = Role.PaidCustomer)]
    public class ResumeController : SmartController {
        private readonly ICustomerService _customerService;
        private readonly IFileService _fileService;
        private readonly IResumeService _resumeService;
        private readonly ILookupService _lookupService;


        public ResumeController(ICustomerService customerService, IFileService fileService, IResumeService resumeService,
                                ILookupService lookupService) {
            _customerService = customerService;
            _fileService = fileService;
            _resumeService = resumeService;
            _lookupService = lookupService;
        }

        public ActionResult Index() {
            return View();
        }

        [HttpPost]
        public ActionResult Index(HttpPostedFileBase resume, string resumeType) {
            if (resume == null) {
                AddError("Please select a resume before clicking the upload button");
                return RedirectToAction("Index");
            }
            Customer customer = _customerService.GetCustomer(CurrentUser);
            Profile profile = customer.Profile;

            return WithinTryCatch<ActionResult>(
                () =>
                {
                    string relativePath = _fileService.SaveResume(resume);
                    // profile.ResumePath = relativePath;
                    profile.SetResumePath(resumeType, relativePath);
                    _customerService.UpdateProfile(profile);
                    AddSuccessMessage("Successfully uploaded the resume");
                    return RedirectToAction("Index");
                },
                x =>
                {
                    AddError("Oops, there was an error in uploading the resume, Please try again");
                    return View();
                }
            );
        }



        public ActionResult KeywordFinder() {
            return View();
        }

        [HttpPost]
        public ActionResult KeywordFinder(string resumeContent) {
            IList<string> missingKeywords = _resumeService.GetMissingKeywords(resumeContent);
            return View("KeywordFinderResults", missingKeywords);
        }

        public ActionResult DownloadResume(string resumeType) {
            Customer customer = _customerService.GetCustomer(CurrentUser);
            Profile profile = customer.Profile;

            var resumePath = profile.GetResumePath(resumeType);
            if (resumePath.IsEmpty()) {
                AddError("You haven't uploaded a resume yet");
                return RedirectToAction("Index");
            }

            var absolutePath = _fileService.GetAbsolutePath(resumePath);
            if (System.IO.File.Exists(absolutePath)) {
                var filename = _fileService.GetFileName(resumePath);
                return WordDoc(absolutePath, filename);
            }
            AddError("You haven't uploaded a resume yet");
            return RedirectToAction("Index");
        }

        public ActionResult DownloadTemplate() {
            return View();
        }

        //TODO:Remove these hardcoded paths
        [HttpPost]
        public ActionResult DownloadTemplate(string resumeType) {
            if (resumeType == "1") {
                return WordDoc(_fileService.GetAbsolutePathOfFile(@"App_Data\Resumes\Chronological.doc"), "Chronological_Template.doc");
            }
            return WordDoc(_fileService.GetAbsolutePathOfFile(@"App_Data\Resumes\Reverse-Chronological.doc"), "Reverse-Chronological_Template.doc");
        }


        //ResumeBuilder stuff
        public ActionResult ResumeBuilder() {
            Customer customer = _customerService.GetCustomer(CurrentUser);
            Resume resume = _resumeService.GetResumeForCustomer(customer);
            ViewData["industryList"] = new SelectList(_lookupService.GetAllIndustries(), "Id", "Name");
            resume = resume ?? GetANewResume(customer);//return a new resume if it doesn't already exist
            return View(resume);
        }

        private Resume GetANewResume(Customer customer) {
            return new Resume
            {
                Customer = customer,
                EducationalDetails = new List<EducationalDetail> { new EducationalDetail(), new EducationalDetail(), new EducationalDetail() },
                JobExperiences = new List<JobExperience> { new JobExperience(), new JobExperience(), new JobExperience() },
                References = new List<Reference> { new Reference(), new Reference(), new Reference() }
            };
        }

        [HttpPost]
        public ActionResult ResumeBuilder([Bind(Exclude = "Id,LastUpdatedOn,LastUpdatedBy")] Resume r, Guid resumeId, Guid customerId) {
            try {
                if (ModelState.IsValid) {
                    if (resumeId.CompareTo(Guid.Empty) == 0) {
                        //resume doesn't exist save a new resume
                        Customer customer = _customerService.GetCustomer(CurrentUser);
                        r.Customer = customer;
                        r.LastUpdatedOn = DateTime.Now;
                        r.LastUpdatedBy = CurrentUser;
                        _resumeService.Save(r);
                    } else {
                        //resume exists update it
                        Resume oldResume = _resumeService.GetResumeById(resumeId);
                        UpdateResume(oldResume, r);
                        _resumeService.Save(oldResume);
                    }
                    AddSuccessMessage("Successfully, Updated resume");
                    return View("Index");
                }
            } catch (Exception ex) {
                //log error
                AddError("Oops, an error occured please try again " + ex.Message + ex.StackTrace);
            }
            return View(r);
        }

        private void UpdateResume(Resume oldResume, Resume newResume) {
            oldResume.Objective = newResume.Objective;
            oldResume.Skills = newResume.Skills;
            for (int i = 0; i < oldResume.JobExperiences.Count; i++) {
                oldResume.JobExperiences[i].CompanyName = newResume.JobExperiences[i].CompanyName;
                oldResume.JobExperiences[i].CompanyIndustryId = newResume.JobExperiences[i].CompanyIndustryId;
                oldResume.JobExperiences[i].CompanyCityState = newResume.JobExperiences[i].CompanyCityState;
                oldResume.JobExperiences[i].FormalTitle = newResume.JobExperiences[i].FormalTitle;
                oldResume.JobExperiences[i].JobDescription = newResume.JobExperiences[i].JobDescription;
                oldResume.JobExperiences[i].StartDate = newResume.JobExperiences[i].StartDate;
                oldResume.JobExperiences[i].EndDate = newResume.JobExperiences[i].EndDate;
            }
            for (int i = 0; i < oldResume.References.Count; i++) {
                oldResume.References[i].FirstName = newResume.References[i].FirstName;
                oldResume.References[i].LastName = newResume.References[i].LastName;
                oldResume.References[i].PhoneNumber = newResume.References[i].PhoneNumber;
            }
            for (int i = 0; i < oldResume.EducationalDetails.Count; i++) {
                oldResume.EducationalDetails[i].SchoolName = newResume.EducationalDetails[i].SchoolName;
                oldResume.EducationalDetails[i].YearObtained = newResume.EducationalDetails[i].YearObtained;
                oldResume.EducationalDetails[i].Degree = newResume.EducationalDetails[i].Degree;
            }

            oldResume.LastUpdatedOn = DateTime.Now;
            oldResume.LastUpdatedBy = CurrentUser;
        }
    }
}
